# -*- coding: UTF-8 -*-
from . import app
from flask import request
from module_software import *
from module_tool import *

# 添加软件列表
@app.route('/interface/software/add', methods=['GET', 'POST'])
def interface_software_add():
    if request.method == 'POST':
        softname = request.form['softname']
        softpath = request.form['softpath']
        soft_obj = Software(softname = softname, softpath = softpath)
        software_add(soft_obj)
        return software_query_all()

# 更新软件列表
@app.route('/interface/software/update', methods=['GET', 'POST'])
def interface_software_update():
    if request.method == 'POST':
        id = request.form['id']
        softname = request.form['softname']
        softpath = request.form['softpath']
        software_update(id, softname, softpath)
        return '更新成功！'

# 查询软件列表id和softname
@app.route('/interface/software/select_id_softname')
def interface_software_select_id_softname():
    result = []
    soft_objs = software_query_id_softname()
    for soft_obj  in soft_objs:
        tmp = {}
        tmp['id'] = soft_obj.id
        tmp['softname'] = soft_obj.softname
        result.append(tmp)
    return json.dumps(result)

# 查询软件列表all
@app.route('/interface/software/select_all')
def interface_software_select_all():
    return software_query_all()

# 删除软件列表
@app.route('/interface/software/delete', methods=['GET', 'POST'])
def interface_software_delete():
    if request.method == 'POST':
        id = request.form['id']
        software_delete_from_id(id)
        return software_query_all()

# 上传软件
@app.route('/interface/software/upload', methods=['GET', 'POST'])
def interface_software_upload():
    if request.method == 'POST':
        result = {}
        softpaths = []
        softids = request.form['softids']
        softids = json.loads(softids)
        ips = request.form['ip'].split(',')
        password = request.form['password']

        for softid in softids:
            softpaths.append(software_query_from_id(softid)[0].strip())

        uploaddir = module_tool_get_conf('software', 'uploaddir')
        for softpath in softpaths:
            for ip in ips:
                status = module_tool_push_file(ip, password, uploaddir+softpath, '/usr/local/src/'+softpath)
                if  status == 1:
                    return 'failed'
        result['ips'] = ips
        result['softpaths'] = softpaths
        return json.dumps(result)
    else:
        return 'failed'